<template>
  <div class="data-source-config">
    <el-form :model="config" label-width="120px">
      <el-form-item label="数据源类型">
        <el-select v-model="config.type" placeholder="请选择数据源类型" @change="handleTypeChange">
          <el-option label="Excel文件" value="excel" />
          <el-option label="JSON文件" value="json" />
          <el-option label="MySQL数据库" value="mysql" />
          <el-option label="CSV文件" value="csv" />
        </el-select>
      </el-form-item>

      <!-- Excel/JSON/CSV 文件上传 -->
      <template v-if="['excel', 'json', 'csv'].includes(config.type)">
        <el-form-item label="上传文件">
          <el-upload
            :auto-upload="false"
            :on-change="handleFileChange"
            :limit="1"
            :file-list="fileList"
          >
            <el-button size="small" type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                {{ config.type === 'excel' ? '支持.xlsx, .xls格式' : config.type === 'json' ? '支持.json格式' : '支持.csv格式' }}
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item v-if="config.type === 'excel'" label="Sheet名称">
          <el-input v-model="config.sheet_name" placeholder="默认为第一个Sheet" />
        </el-form-item>
      </template>

      <!-- MySQL 数据库配置 -->
      <template v-if="config.type === 'mysql'">
        <el-form-item label="主机地址">
          <el-input v-model="config.host" placeholder="如：localhost" />
        </el-form-item>

        <el-form-item label="端口">
          <el-input v-model="config.port" placeholder="默认：3306" />
        </el-form-item>

        <el-form-item label="数据库名">
          <el-input v-model="config.database" placeholder="请输入数据库名" />
        </el-form-item>

        <el-form-item label="用户名">
          <el-input v-model="config.username" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="密码">
          <el-input v-model="config.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>

        <el-form-item label="查询SQL">
          <el-input
            v-model="config.query"
            type="textarea"
            :rows="4"
            placeholder="请输入SQL查询语句，如：SELECT * FROM users"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="testConnection">测试连接</el-button>
        </el-form-item>
      </template>

      <!-- 数据预览 -->
      <el-form-item v-if="previewData.length > 0" label="数据预览">
        <el-table :data="previewData" border max-height="300">
          <el-table-column
            v-for="(value, key) in previewData[0]"
            :key="key"
            :prop="key"
            :label="key"
            min-width="120"
          />
        </el-table>
        <div style="margin-top: 10px; color: #909399;">
          共 {{ previewData.length }} 条数据
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { testDataSource, previewDataSource } from '@/api'

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:modelValue'])

const config = reactive({
  type: 'excel',
  file: null,
  sheet_name: '',
  host: 'localhost',
  port: '3306',
  database: '',
  username: '',
  password: '',
  query: '',
  ...props.modelValue
})

const fileList = ref([])
const previewData = ref([])

watch(config, (val) => {
  emit('update:modelValue', val)
}, { deep: true })

const handleTypeChange = () => {
  previewData.value = []
  fileList.value = []
}

const handleFileChange = (file) => {
  config.file = file.raw
  fileList.value = [file]
  
  // 如果是JSON文件，可以直接预览
  if (config.type === 'json') {
    const reader = new FileReader()
    reader.onload = (e) => {
      try {
        const data = JSON.parse(e.target.result)
        previewData.value = Array.isArray(data) ? data.slice(0, 5) : [data]
      } catch (error) {
        ElMessage.error('JSON文件格式错误')
      }
    }
    reader.readAsText(file.raw)
  }
}

const testConnection = async () => {
  try {
    const result = await testDataSource({
      type: config.type,
      host: config.host,
      port: config.port,
      database: config.database,
      username: config.username,
      password: config.password
    })
    
    if (result.success) {
      ElMessage.success('连接成功')
      
      // 如果有查询语句，执行预览
      if (config.query) {
        await loadPreview()
      }
    } else {
      ElMessage.error('连接失败：' + result.message)
    }
  } catch (error) {
    ElMessage.error('连接失败：' + error.message)
  }
}

const loadPreview = async () => {
  try {
    const result = await previewDataSource(config.id, {
      query: config.query,
      limit: 5
    })
    
    previewData.value = result.data || []
  } catch (error) {
    ElMessage.error('预览失败：' + error.message)
  }
}
</script>

<style scoped>
.data-source-config {
  padding: 20px;
}
</style>
